<template>
    <div class="userhome-content">
        <van-icon class="back-btn" name="arrow-left" @click="$router.go(-1)"/>
        <van-icon name="ellipsis" class="del-btn" v-if="$route.query._id !== userId && friendState === 1" @click="showPopup=true"/>
        <!-- 删除好友弹出层 -->
        <van-popup 
            v-model="showPopup"
            position="bottom" 
            :style="{ height: '1.4667rem' }"
        >
            <div class="out-group" @click="delFriend">删除好友</div>
        </van-popup>
        <div class="bg">
            <BackgroundCanvas/>
        </div>
        <div class="content">
            <div class="top">
                <div class="user-pic" @click="lookPic($baseUrl + userHomeData.imgUrl)">
                    <img :src="$baseUrl + userHomeData.imgUrl" alt="">
                </div>
                <!-- 头像弹出层 -->
                <div class="user-nickAndcode">
                    <div class="user-nick">{{ userHomeData.nick }}</div>
                    <div class="user-code">WaiFCode：{{ userHomeData.WaiFCode }}</div>
                </div>
            </div>
            <div class="user-info">
                <div class="self-info">
                    <img src="@/assets/zhengjian.png" alt="">
                    <span v-for="(item,index) in userHomeInfo" :key="index">{{ item }}</span>
                </div>
                <div class="phone">
                    <img src="@/assets/dazhaohu.png" alt="">
                    电话：{{ userHomeData.phone }}
                </div>
                <div class="sign">
                    <img src="@/assets/youxi.png" alt="">
                    <span>个性签名：{{ userHomeData.sign }}</span>
                </div>
                <div class="space" @click="goUserSpace(userHomeData._id)">
                    <img src="@/assets/xiangce.png" alt="">
                    {{ userHomeData.nick }}的空间（去看看）
                    <van-icon name="arrow" class="icon-right"/>
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="send-btn" @click="handleBtnClick">{{ btnText }}</div>
        </div>
    </div>
</template>

<script>
import BackgroundCanvas from '@/components/BackgroundCanvas'
import { reqGetUserhome, reqAddFriend, reqDelFriend } from '@/api'
import { mapState } from 'vuex'
import { Toast } from 'vant'
import { ImagePreview, Dialog } from 'vant'
export default {
    components: {
        BackgroundCanvas
    },
    data() {
        return {
            userHomeInfo: [],
            userHomeData: {},
            friendState: null,
            showPopup: false
        }
    },
    computed: {
        ...mapState({
            userId: state => state.login.userInfo._id
        }),
        // 底部按钮文字
        btnText() {
            const { friendState } = this
            if (friendState === 0) {
                return '申请中'
            } else if (friendState === 1) {
                return '发消息'  // 已为好友
            } else if (friendState === 3) {
                return '编辑资料'  // 该用户是自己（4为编辑资料）
            } else {
                return '加好友'
            }
        }
    },
    methods: {
        // 获取用户主页数据
        async getUserhome() {
            // 需要将自己的id和浏览器地址路径中的id发给后端进行比较（看是自己主页，还是对方主页）
            let _id = this.userId
            let urlId = this.$route.query._id
            let res = await reqGetUserhome({_id, urlId})
            if (res.status === 200) {
                const { sex, age, birthday, start } = res.data.user
                let newBirthday = this.getBirthday(birthday)
                this.userHomeInfo = [sex, age + '岁', newBirthday, start]
                this.userHomeData = res.data.user
                this.friendState = res.data.friendState
            } else {
                Toast(res.msg)
            }
        },
        // 查看用户头像
        lookPic(imgUrl) {
            ImagePreview({
                images: [imgUrl],
                loop: false,
                closeable: true
            })
        },
        // 计算生日（月、日）
        getBirthday(birthday) {
            let dateArr = birthday.split('-')
            return dateArr[1] + '月' + dateArr[2] + '日'
        },
        // 底部按钮（添加好友、发消息、编辑资料）
        async handleBtnClick() {
            /**
             * friendState => 0  申请中
             * friendState => 1  发消息
             * friendState => 2(null) 加好友
             * friendState => 3  编辑资料
             */
            let { friendState } = this
            let userId = this.userId
            let friendId = this.$route.query._id
            if (friendState === 0) {
                // 申请中，不允许点击
                return
            } else if (friendState === 3) {
                // 编辑资料
                this.$router.push({
                    path: '/updateinfo/个人信息',
                    query: {
                        _id: userId
                    }
                })
            } else if (friendState === 1) {
                // 发消息
                this.$router.push({
                    path: '/messagedetails/friendChat',
                    query: {
                        _id: friendId
                    }
                })
            } else {
                // 添加好友
                let res = await reqAddFriend({
                    userId,
                    friendId
                })
                if (res.status === 200) {
                    this.friendState = 0
                    // 触发socket
                    this.$socket.emit('apply_notice', friendId)
                }
                Toast(res.msg)
            }
        },
        // 删除好友
        delFriend() {
            Dialog.confirm({
                title: '温馨提示',
                message: '确定要删除该好友吗？'
            }).then(async() => {
                // 确定
                let ids = {
                    userId: this.userId,
                    friendId: this.$route.query._id
                }
                let res = await reqDelFriend(ids)
                if (res.status === 200) {
                    this.$router.push('/contacts')
                }
                Toast(res.msg)
            }).catch(() => {
                // 取消
                this.showPopup = false
            })
        },
        // 去用户空间
        goUserSpace(_id) {
            this.$router.push({
                path: '/spacedetails',
                query: {
                    _id
                }
            })
        }
    },
    mounted() {
        this.getUserhome()
    }
}
</script>

<style lang="less" scoped>
.userhome-content {
    position: relative;
}
.back-btn {
    position: fixed;
    left: .4rem;
    top: .4rem;
    font-size: .5333rem;
    color: #fff;
    font-weight: 600;
}
.del-btn {
    position: fixed;
    right: .4rem;
    top: .4rem;
    font-size: .6rem;
    color: #fff;
    font-weight: 600;
}
.bg {
    width: 100%;
    height: 4.8667rem;
}
.content {
    width: 100%;
    height: 10.6667rem;
    background-color: #fff;
    // background-color: skyblue;
    padding: .4rem;
    box-sizing: border-box;
    left: 0;
    top: 4.4rem;
    position: absolute;
    border-radius: .5333rem .5333rem 0 0;
    .top {
        width: 100%;
        height: 2.3333rem;
        display: flex;
        align-items: center;
        margin-bottom: .3333rem;
        .user-pic {
            width: 2.3333rem;
            height: 2.3333rem;
            border-radius: 50%;
            overflow: hidden;
            margin-right: .4rem;
            img {
                width: 100%;
                height: 100%;
            }
        }
        .user-nickAndcode {
            flex: 1;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            .user-nick {
                font-size: .4rem;
                font-weight: 700;
                margin-bottom: .2667rem;
            }
            .user-code {
                color: #7a7a7a;
                font-size: .24rem;
            }
        }
    }
    .user-info {
        font-size: .3333rem;
        color: #4d4d4d;
        img {
            width: .6667rem;
            height: .6667rem;
        }
        .self-info {
            width: 100%;
            height: .6667rem;
            display: flex;
            align-items: center;
            margin-bottom: .3333rem;
            span {
                display: inline-block;
                padding: 0 .2667rem;
                border-right: .0133rem solid #7a7a7a;
            }
            span:nth-last-child(1) {
                border: none;
            }
        }
        .sign, .phone, .space {
            width: 100%;
            display: flex;
            align-items: center;
            margin-bottom: .3333rem;
            font-size: .3333rem;
            img {
                margin-right: .2rem;
            }
            span {
                line-height: .4667rem;
            }
        }
        .icon-right {
            margin-left: auto;
        }
    }
}
.bottom {
    width: 100%;
    height: 1.6667rem;
    background-color: #fff;
    border-top: 0.04rem solid #dbdada;
    padding: .2667rem .4rem;
    box-sizing: border-box;
    position: fixed;
    left: 0;
    bottom: 0;
    .send-btn {
        width: 100%;
        height: 100%;
        background-color: #3c98ff;
        border-radius: .1333rem;
        color: #fff;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 0.4rem;
    }
}
.out-group {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 0.4rem;
    color: #f06262;
}
</style>

<style>
.van-overlay {
    background-color: rgba(0,0,0,.7);
}
</style>